package firstShallowPersistencePackagev;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Hashtable;

/*
 * Created on 16/08/2005
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author malice
 * 
 *         TODO To change the template for this generated type comment go to
 *         Window - Preferences - Java - Code Style - Code Templates
 */
public class Broker implements Serializable {
	private static final long serialVersionUID = 42L;

	private String bFileName;
	private Hashtable<Integer, TableEntry> apObjs;
	private Integer next;

	public Broker() {
		super();
		this.bFileName = null;
		this.apObjs = new Hashtable<Integer, TableEntry>();
		next = new Integer(0);
	}

	public Broker(String bFName) {
		super();
		this.bFileName = bFName;
		this.apObjs = new Hashtable<Integer, TableEntry>();
		next = new Integer(0);
	}

	public TableEntry getEntry(Integer id) {
		return ((TableEntry) apObjs.get(id));
	}

	public Object getObj(Integer id) {
		TableEntry entr;
		entr = this.getEntry(id);
		return (entr.getObj(id));
	}

	public Integer put(Object o) {

		int intAux;
		TableEntry entr;

		entr = new TableEntry(next, o);
		apObjs.put(next, entr);
		intAux = next.intValue();
		next = new Integer(intAux + 1);
		return (new Integer(intAux));
	}

	public void write(Integer id) {
		TableEntry entr;
		entr = (TableEntry) apObjs.get(id);
		entr.write();
	}

	public void close(Integer id) {
		TableEntry entr;
		entr = (TableEntry) apObjs.get(id);
		entr.close();
	}

	public void close() {
		for (Enumeration e = apObjs.keys(); e.hasMoreElements();) {
			Integer key = (Integer) e.nextElement();
			write(key);
			close(key);
		}
		if (bFileName != null) {
			try {
				FileOutputStream fileOut = new FileOutputStream(bFileName);
				ObjectOutputStream out = new ObjectOutputStream(fileOut);
				out.writeObject(this);
			} catch (Exception e) {
				javax.swing.JOptionPane.showMessageDialog(null,
						"writing file Exception: " + e);
			}
			;
		}
	}

	public void display(Integer id) {
		TableEntry entr;
		entr = (TableEntry) apObjs.get(id);
		entr.display();
	}

	public void display() {
		for (Enumeration e = apObjs.keys(); e.hasMoreElements();) {
			Integer key = (Integer) e.nextElement();
			display(key);
		}
	}

	public Object runMethod(Object proxy, Method me, Object[] args, Integer id)
			throws Throwable {
		Object result;
		TableEntry entr;
		entr = getEntry(id);
		try {
			result = entr.runMethod(proxy, me, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
		return result;
	}
}
